var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
const {verifyToken , judgeToken , decodeToken} = require('../../tool/jwt')
const {setDate} = require('../../tool/date')

const Rides = require('ioredis');

module.exports = (pool) => {

// 创建 Redis 客户端
const rides = new Rides({
  host: '127.0.0.1',
  port: 6379
});
// 处理 Redis 连接错误
rides.on('error', (err) => {
    console.error('Redis error:', err);
});
// 连接 Redis
rides.on('connect', () => {
  console.log('Connected to Redis');
});


//阿里云发送短信配置
const Dysmsapi20170525 = require('@alicloud/dysmsapi20170525');
const OpenApi = require('@alicloud/openapi-client');
const config = new OpenApi.Config({
    // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
    accessKeyId: 'LTAI5tNaJgC99iUqPGHwAEzn',
    // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
    accessKeySecret: "qqTthEdqusULCFfSJtyTuTpTVPdL2g",
});
config.endpoint = `dysmsapi.aliyuncs.com`;


//验证token方法
const tokenvalidate = (req,res,next)=>{
  try {
    const token = req.headers.token;
    const v = verifyToken(token,'shop_key')
    if(v != null){
      const v2 = judgeToken(token,'shop_key')
      if(v2 ==0){
        next()
      }else{
        return res.send({data:{msg:'token已过期',code:'500'}})
      }

    }else{
      return res.send({data:{msg:'token已过期',code:'500'}})
    }
    
  } catch (error) {
    console.log(error)
    res.status(500).send('Error');
    process.exit(1)
  }
}

//生成验证码
function getcode() {
    return Math.floor(Math.random() * 9000) + 1000;
}


//手机号验证码
router.post('/sendcode', async function (req, res, next) {
try {
    const {phone} = req.body
    const code = getcode()
    const client = new Dysmsapi20170525.default(config);
    const sendSmsRequest = new Dysmsapi20170525.SendSmsRequest({
        signName: '阿里云短信测试',
        templateCode: 'SMS_154950909',
        phoneNumbers: '18522374667',
        templateParam: `{"code":"${code}"}`,
    });
    //发送短信
    // const result = await client.sendSmsWithOptions(sendSmsRequest, {}, (err, resp) => {
    //     if (err) {
    //         console.error(err);
    //     } else {
    //         console.log(resp);
    //     }
    // });

    await rides.set(phone,code,(err)=>{
        if (err) {
            res.status(500).send({data:{code:500,msg:'发送失败'}});
          } else {
            res.send({data:{code:200,msg:'发送成功'}});
          }
    })
    
    
} catch (error) {
    console.log(error)
    res.status(500).send({data:{msg:"服务异常",code:500}});
    process.exit(1)
}
    
     
});

//登入并注册
router.post('/login', async (req, res, next) =>{
  res.setHeader('Access-Control-Allow-Origin','*')
  if(!req.body.code){
    return res.send({data:{msg:"验证码不能为空",code:'500'}});
  }
  if(!req.body.phone) {
    return res.send({data:{msg:"手机号不能为空",code:'500'}});
  }
  next();
},async (req,res)=>{
  try {
    const {code,phone} = req.body
    const result = await rides.get(phone)
    
    const connection = await pool.promise().getConnection()
    var user = await connection.query(`select * from user where phone= ?`,phone)
    
    if(user[0].length !== 0){
      connection.release()
      if(result == code){
        if(user[0][0].state == 1){
          res.send({data:{msg:"该账号异常",code:500}})
        }
        const token = generateToken(user[0][0])
        res.send({data:{msg:"登录成功",code:200,token:token,nickname:user[0][0].nickname,user_img:user[0][0].avatar}}) 
      }else{
        res.send({data:{msg:"验证码错误",code:500}}) 
      }
    }else{
      
      if(result == code){
        const firstPart = phone.substring(0, 3);
        const lastPart = phone.substring(7);
        const hiddenPart = "****";
        let nickname = firstPart + hiddenPart + lastPart
        var newuser = await connection.query(`INSERT INTO user ( phone,nickname,create_date,state) VALUES (?,?,?,?)`,[phone,nickname,setDate(),0])
        connection.release()
        if(newuser[0].insertId){
          const token = generateToken({phone:phone,id:newuser[0].insertId,nickname:nickname})
          res.send({data:{msg:"登录成功",code:200,token:token,nickname,user_img:user[0][0].avatar}})
        }else{
          res.send({data:{msg:"注册失败",code:500}})
        }
      }else{
        connection.release()
        res.send({data:{msg:"验证码错误",code:500}})
      }
      
    }

  } catch (error) {
    console.log(error)
    res.status(500).send({data:{msg:"服务异常",code:500}});
    process.exit(1)
  }
})
//获取用户地址列表
router.get('/getaddress',(req, res, next) => { tokenvalidate(req, res, next) },async(req,res)=>{
  try {
    // 获取用户信息
    const user = decodeToken(req.headers.token);
    if (user == null) return res.send({ data: { msg: 'token已过期', code: 500 } });
    const connection = await pool.promise().getConnection();
    const result1 = await connection.query('select * from addresses where uid = ?',[user.id])
    connection.release()
    res.send({data:{msg:"获取成功",code:200,data:result1[0]}})
  } catch (error) {
    console.error(error);
    res.status(500).send({ data: { msg: "服务异常", code: 500 } });
    process.exit(1)
  }
})
//删除用户地址列表
router.get('/deleteaddress/:id',(req, res, next) => { tokenvalidate(req, res, next) },async(req,res)=>{
  try {
    const {id} = req.params
    const connection = await pool.promise().getConnection();
    const result1 = await connection.query('delete from addresses where id = ?',[id])
    connection.release()
    if(result1[0].affectedRows){
      res.send({data:{msg:"删除成功",code:200}})
    }else{
      res.send({data:{msg:"删除失败",code:500}})
    }
  } catch (error) {
    console.error(error);
    res.status(500).send({ data: { msg: "服务异常", code: 500 } });
    process.exit(1)
  }
})
//添加用户收货地址
router.post('/addaddress',(req, res, next) => { tokenvalidate(req, res, next) },async(req,res)=>{
  try {
    // 获取用户信息
    const user = decodeToken(req.headers.token);
    if (user == null) return res.send({ data: { msg: 'token已过期', code: 500 } });
    const {name,phone,address} = req.body
    const connection = await pool.promise().getConnection();
    const result1 = await connection.query('INSERT INTO addresses (uid,receiver_name,receiver_phone,address) VALUES (?,?,?,?)',[user.id,name,phone,address])
    connection.release()
    if(result1[0].insertId){
      res.send({data:{msg:"添加成功",code:200}})
    }else{
      res.send({data:{msg:"添加失败",code:500}})
    }
  } catch (error) {
    console.error(error);
    res.status(500).send({ data: { msg: "服务异常", code: 500 } });
    process.exit(1)
  }
})
  

//生成token
function generateToken(user) {
  const payload = {
    phone: user.phone,
    id: user.id,
    nickname: user.nickname,
  };
  const secretKey = 'shop_key'
  const options = {
    expiresIn: '1d' 
  };
  const token = jwt.sign(payload, secretKey, options);
  return token;
}

//进程崩溃，关闭数据库连接
process.on('SIGINT', () => {
    pool.end();
    redis.disconnect();
    process.exit(0);
})

  //返回路由
  return router

}

